package com.example.springbootusecase.hardware;

import static org.bytedeco.ffmpeg.global.avcodec.*;
import static org.bytedeco.ffmpeg.global.avutil.*;
import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.Mat;
import static org.bytedeco.opencv.global.opencv_imgproc.COLOR_BGR2GRAY;
import static org.bytedeco.opencv.global.opencv_imgproc.cvtColor;
import java.io.File;
import java.io.IOException;

/**
 * 摄像头调用
 * @author Think
 */
public class Camara {
    public static void main(String[] args) throws IOException {
        // 创建摄像头抓取器（0表示默认摄像头）
        FrameGrabber grabber = FrameGrabber.createDefault(0);
        // 启动摄像头
        grabber.start();
        // 捕获并显示视频帧
        catchAndShow(grabber);
        // 保存图片
        savePhoto(grabber);
        // 保存视频
        saveVideo(grabber);
        // 灰度处理
        grayScaleProcessing(grabber);
        grabber.stop();
    }

    private static void grayScaleProcessing(FrameGrabber grabber) throws IOException {
        CanvasFrame canvas = new CanvasFrame("Gray Camera");
        OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();

        while (canvas.isVisible()) {
            Frame frame = grabber.grab();
            // Frame转OpenCV Mat
            Mat mat = converter.convert(frame);
            // 转换为灰度图像
            cvtColor(mat, mat, COLOR_BGR2GRAY);
            Frame processedFrame = converter.convert(mat);
            canvas.showImage(processedFrame);
        }
        canvas.dispose();

    }

    private static void saveVideo(FrameGrabber grabber) throws IOException {
        // 获取摄像头帧率
        double frameRate = grabber.getFrameRate();
        if (frameRate <= 0) frameRate = 30; // 默认30fps

        // 创建视频录制器
        FrameRecorder recorder = FrameRecorder.createDefault("output.mp4",
                grabber.getImageWidth(), grabber.getImageHeight());
        recorder.setVideoCodec(AV_CODEC_ID_H264);
        recorder.setFormat("mp4");
        recorder.setPixelFormat(AV_PIX_FMT_YUV420P); // 必须设置
        recorder.setFrameRate(frameRate);
        recorder.setVideoBitrate(2_000_000); // 2 Mbps

        // 手动设置时间基（替代旧版setVideoTimebase）
        recorder.setVideoOption("time_base", "1/" + (int) frameRate);

        recorder.start();

        CanvasFrame canvas = new CanvasFrame("Camera");
        while (canvas.isVisible()) {
            Frame frame = grabber.grab();
            canvas.showImage(frame);
            recorder.record(frame);
        }

        recorder.stop();
        canvas.dispose();
    }

    private static void savePhoto(FrameGrabber grabber) throws IOException {
        Java2DFrameConverter converter = new Java2DFrameConverter();
        java.awt.image.BufferedImage image = converter.convert(grabber.grab());
        javax.imageio.ImageIO.write(image, "jpg", new File("snapshot.jpg"));
    }

    private static void catchAndShow(FrameGrabber grabber) throws FrameGrabber.Exception {
        // 捕获并显示视频帧
        CanvasFrame canvas = new CanvasFrame("Camera");
        // 窗口存在时持续运行
        while (canvas.isVisible()) {
            // 抓取一帧视频
            Frame frame = grabber.grab();
            // 在窗口中显示帧
            canvas.showImage(frame);
        }
        // 销毁窗口
        canvas.dispose();
    }
}